package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> sendMes(@RequestBody User user, HttpServletRequest request) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //系统随机生成的4位验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("验证码为:{}", code);
            //给手机号发送验证码,在这里我们可以模拟拿到了验证码,然后直接登录
            // SMSUtils.sendMessage(phone,code);
            //设置一个session存数据代表已经登录过
            request.getSession().setAttribute(user.getPhone(), code);//TODO
            return R.success("发送短信成功");
        }
        return R.error("发送短信失败");
    }

    @PostMapping("login")
    public R<String> login(@RequestBody Map map, HttpServletRequest request) {
        //1.用户写的验证码
        String code = (String) map.get("code");
        String phone = (String) map.get("phone");
        String ssessionCode = (String) request.getSession().getAttribute(phone);

        if (code == null || !code.equals(ssessionCode)) {
            //验证码有误
            return R.error("验证码输入有误,登录失败");
        }//否则登录成功
        request.getSession().removeAttribute(phone);
        //1.判断用户是否存在,不存在就自动添加.需要userservice
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(userLambdaQueryWrapper);
        if (user == null) {
            //用户不存在
            //保存用户到数据库
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }//用户存在,登录成功
        request.getSession().setAttribute("user",user);
       return R.success("登录成功");
    }
}

